import 'braft-editor/dist/index.css'
import React from 'react'
import BraftEditor from 'braft-editor'
import { ContentUtils } from 'braft-utils'
import PropTypes from "prop-types";
import { FileImageOutlined } from '@ant-design/icons';
import { Upload } from 'antd'
import './style.less'
import '@/style/view-style/editor.less'
const controls = [
  'undo', 'redo', 'separator',
  'font-size',
  'text-color', 'bold', 'italic', 'underline', 'strike-through', 'separator',
  'superscript', 'subscript', 'remove-styles', 'emoji', 'separator', 'text-indent', 'text-align', 'separator',
  'headings', 'list-ul', 'list-ol', 'blockquote', 'separator',
  'link', 'separator', 'hr', 'separator',
  'separator',
  'clear'
]
class TheQuill extends React.Component {
  state = {
    editorState: BraftEditor.createEditorState(this.props.defaultValue),
    readOnly:this.props.readOnly
  }
  /**
   * @desc 富文本修改事件
   * */
  handleChange = (editorState) => {
    this.setState({ editorState })
    this.props.setNewsContent(editorState.toHTML());
  }
  /**
   * @desc 上传图片事件
   * */
  uploadHandler = (param) => {
    if (!param.file) {
      return false
    }
    let formdata = new FormData()
    formdata.append('file', param.file)
    // React.$postMedia(React.$BaseUrl +'/oss/image/upload', formdata).then(res => {
    React.$postMedia('https://management.hqmpet.com/management/oss/image/upload', formdata).then(res => {
      this.setState({
        editorState: ContentUtils.insertMedias(this.state.editorState, [{
          type: 'IMAGE',
          url: res.data
        }])
      })
    })
  }
  render() {
    const {readOnly} = this.state
    const extendControls = [
      {
        key: 'antd-uploader',
        type: 'component',
        component: (
          <Upload
            accept="image/*"
            showUploadList={false}
            customRequest={this.uploadHandler}
          >
            {/* 这里的按钮最好加上type="button"，以避免在表单容器中触发表单提交，用Antd的Button组件则无需如此 */}
            <button type="button" className="control-item button upload-button" data-title="插入图片">
              <FileImageOutlined />
            </button>
          </Upload>
        )
      }
    ]
    return (
      <div>
        <div className="editor-wrapper">
          <BraftEditor
            value={this.state.editorState}
            onChange={this.handleChange}
            controls={controls}
            extendControls={extendControls}
            readOnly={readOnly}
          />
        </div>
      </div>
    )
  }
}
TheQuill.propTypes = {
  value: PropTypes.string,
  setNewsContent: PropTypes.func,
};
TheQuill.defaultProps = {
  value: null
};
export default TheQuill
